package mysql

import (
	"fmt"
	"gin/app/http/global"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
	"time"
)

var (
	err error
	mu  sync.Mutex
)

func InitMysql() error {
	mu.Lock()
	defer mu.Unlock()
	host := viper.GetString("mysql.host")
	port := viper.GetString("mysql.port")
	user := viper.GetString("mysql.user")
	password := viper.GetString("mysql.password")
	database := viper.GetString("mysql.database")
	charset := viper.GetString("mysql.charset")
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True", user, password, host, port, database, charset)
	DB, err := gorm.Open(mysql.Open(args), &gorm.Config{})
	sqlDB, err := DB.DB()
	sqlDB.SetMaxIdleConns(10)  //最大空闲连接数
	sqlDB.SetMaxOpenConns(100) //最大打开连接数
	sqlDB.SetConnMaxLifetime(time.Hour)

	if err != nil {
		return err
	}
	DB.Debug()

	global.DB = DB
	fmt.Println("mysql连接成功")
	return nil
}
